package com.zhiwen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhiwen.domain.dto.UserSettingsDTO;
import com.zhiwen.domain.entity.UserSettings;
import com.zhiwen.mapper.UserSettingsMapper;
import com.zhiwen.service.UserSettingsService;
import com.zhiwen.domain.vo.UserSettingsVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 用户设置服务实现类
 */
@Service
@RequiredArgsConstructor
public class UserSettingsServiceImpl extends ServiceImpl<UserSettingsMapper, UserSettings> implements UserSettingsService {

    @Override
    public UserSettingsVO getUserSettings(Long userId) {
        // 查询用户设置
        LambdaQueryWrapper<UserSettings> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserSettings::getUserId, userId);
        UserSettings settings = getOne(wrapper);

        // 如果不存在，则创建默认设置
        if (settings == null) {
            settings = createDefaultSettings(userId);
        }

        // 转换为视图对象
        return convertToVO(settings);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserSettingsVO updateUserSettings(UserSettingsDTO settingsDTO) {
        // 查询用户设置
        LambdaQueryWrapper<UserSettings> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserSettings::getUserId, settingsDTO.getUserId());
        UserSettings settings = getOne(wrapper);

        // 如果不存在，则创建默认设置
        if (settings == null) {
            settings = createDefaultSettings(settingsDTO.getUserId());
        }

        // 更新设置
        BeanUtils.copyProperties(settingsDTO, settings);
        settings.setUpdateTime(LocalDateTime.now());
        updateById(settings);

        // 返回更新后的设置
        return convertToVO(settings);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserSettingsVO updateNotificationSettings(Long userId, String type, boolean enabled) {
        // 查询用户设置
        UserSettings settings = getUserSettingsByUserId(userId);

        // 根据类型更新通知设置
        Integer value = enabled ? 1 : 0;
        switch (type) {
            case "answer":
                settings.setNotifyOnAnswer(value);
                break;
            case "comment":
                settings.setNotifyOnComment(value);
                break;
            case "accept":
                settings.setNotifyOnAccept(value);
                break;
            case "like":
                settings.setNotifyOnLike(value);
                break;
            default:
                throw new IllegalArgumentException("无效的通知类型: " + type);
        }

        // 更新设置
        settings.setUpdateTime(LocalDateTime.now());
        updateById(settings);

        // 返回更新后的设置
        return convertToVO(settings);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserSettingsVO updatePrivacySettings(Long userId, String type, boolean enabled) {
        // 查询用户设置
        UserSettings settings = getUserSettingsByUserId(userId);

        // 根据类型更新隐私设置
        Integer value = enabled ? 1 : 0;
        switch (type) {
            case "online_status":
                settings.setShowOnlineStatus(value);
                break;
            case "messages":
                settings.setAllowMessages(value);
                break;
            default:
                throw new IllegalArgumentException("无效的隐私设置类型: " + type);
        }

        // 更新设置
        settings.setUpdateTime(LocalDateTime.now());
        updateById(settings);

        // 返回更新后的设置
        return convertToVO(settings);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserSettingsVO updateInterfaceSettings(Long userId, Boolean darkMode, String language) {
        // 查询用户设置
        UserSettings settings = getUserSettingsByUserId(userId);

        // 更新界面设置
        if (darkMode != null) {
            settings.setDarkMode(darkMode ? 1 : 0);
        }

        if (language != null && !language.isEmpty()) {
            settings.setLanguage(language);
        }

        // 更新设置
        settings.setUpdateTime(LocalDateTime.now());
        updateById(settings);

        // 返回更新后的设置
        return convertToVO(settings);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserSettingsVO resetUserSettings(Long userId) {
        // 查询用户设置
        LambdaQueryWrapper<UserSettings> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserSettings::getUserId, userId);
        UserSettings settings = getOne(wrapper);

        // 如果存在，则删除
        if (settings != null) {
            removeById(settings.getId());
        }

        // 创建默认设置
        UserSettings defaultSettings = createDefaultSettings(userId);

        // 返回默认设置
        return convertToVO(defaultSettings);
    }

    /**
     * 根据用户ID获取设置，如果不存在则创建默认设置
     */
    private UserSettings getUserSettingsByUserId(Long userId) {
        LambdaQueryWrapper<UserSettings> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserSettings::getUserId, userId);
        UserSettings settings = getOne(wrapper);

        // 如果不存在，则创建默认设置
        if (settings == null) {
            settings = createDefaultSettings(userId);
        }

        return settings;
    }

    /**
     * 创建默认用户设置
     */
    private UserSettings createDefaultSettings(Long userId) {
        UserSettings settings = new UserSettings();
        settings.setUserId(userId);
        settings.setNotifyOnAnswer(1);
        settings.setNotifyOnComment(1);
        settings.setNotifyOnAccept(1);
        settings.setNotifyOnLike(1);
        settings.setShowOnlineStatus(1);
        settings.setAllowMessages(1);
        settings.setLanguage("zh_CN");
        settings.setDarkMode(0);
        settings.setCreateTime(LocalDateTime.now());
        settings.setUpdateTime(LocalDateTime.now());
        save(settings);
        return settings;
    }

    /**
     * 将实体转换为视图对象
     */
    private UserSettingsVO convertToVO(UserSettings settings) {
        UserSettingsVO vo = new UserSettingsVO();
        BeanUtils.copyProperties(settings, vo);
        return vo;
    }
}
